package mqigdcom.mqigd.ui;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import mqigdcom.mqigd.R;

/**
 * 自定义的定位弹出框
 */
public class CustomLocationDialog extends DialogFragment {

    private TextView mTvTips;// 定位提示文本框
    private Handler mHandler;// 消息处理句柄

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme_NoDimDialog);
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 1) {
                    dismiss();
                }
                return false;
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null && dialog.getWindow() != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int dialogSize = (int) (dm.widthPixels * 0.35);
            dialog.getWindow().setLayout(dialogSize, dialogSize);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_location, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setCancelable(false);
        mTvTips = (TextView) view.findViewById(R.id.dialog_location_tips_tv);
    }

    /**
     * 定位成功，2秒后自动关闭该弹出框
     *
     * @param succeedTxt 成功的文字
     */
    public void locationCompleted(String succeedTxt) {
        if (mTvTips != null) {
            mTvTips.setText(succeedTxt);
        }
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(1, 3000);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }
}
